package com.jzg.common.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.alibaba.fastjson.JSON;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jzg.common.render.RenderBean;

import sun.misc.BASE64Decoder;

@SuppressWarnings("restriction")
public class YTUtil {

	protected final static Log log = Log.getLog(YTUtil.class);

	/**
	 * 请求地址
	 */
	private static String POST_URL = "http://86.81.3.139:9500/face/v1/algorithm/recognition/face_pair_verification";

	/**
	 * 数据库图片类型
	 */
	private static int DATABASE_IMAGE_TYPE = 4;

	/**
	 * 查询图片类型
	 */
	private static int QUERY_IMAGE_TYPE = 303;

	public static RenderBean httpURLConnectionPOSTForSL(String queryXP, String dbXP) {

		RenderBean result = new RenderBean();

		if (StrKit.isBlank(queryXP) | StrKit.isBlank(dbXP)) {
			result.setCode(500);
			result.setMessage("参数有误！");
			return result;
		}

		try {

			String reqJson = "{\"database_image_content\": \"" + base64ToBase64(dbXP) + "\",\"database_image_type\": "
					+ DATABASE_IMAGE_TYPE + ",\"query_image_content\": \"" + base64ToBase64(queryXP)
					+ "\",\"query_image_type\": " + QUERY_IMAGE_TYPE + "}";

			// 传递参数
			URL url = new URL(POST_URL);
			// 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接 (标识一个url所引用的远程对象连接)
			// 此时cnnection只是为一个连接对象,待连接中
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
			connection.setDoOutput(true);
			// 设置连接输入流为true
			connection.setDoInput(true);
			// 设置请求方式为post
			connection.setRequestMethod("POST");
			// post请求缓存设为false
			connection.setUseCaches(false);
			// 设置该HttpURLConnection实例是否自动执行重定向
			connection.setInstanceFollowRedirects(true);
			connection.addRequestProperty("from", "sfzh"); // 来源哪个系统
			connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

			// 建立连接 (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
			connection.connect();
			// 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
			DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());

			// 将参数输出到连接
			dataout.writeBytes(reqJson);
			// 输出完成后刷新并关闭流
			dataout.flush();
			dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
			// System.out.println(connection.getResponseCode());
			// 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
			BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			StringBuilder sb = new StringBuilder(); // 用来存储响应数据

			// 循环读取流,若不到结尾处
			while ((line = bf.readLine()) != null) {
				// sb.append(bf.readLine());
				sb.append(line).append(System.getProperty("line.separator"));
			}
			bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
			connection.disconnect(); // 销毁连接

			String out = sb.toString();

			if (!StrKit.isBlank(out)) {
				Map<String, Object> outMap = JSON.parseObject(out);
				if (outMap != null && outMap.size() > 0) {
					if (StrKit.equals("0", outMap.get("rtn") + "")) {
						if (StrKit.equals("0", outMap.get("pair_verify_result") + "")) {
							result.setCode(200);
							result.setMessage("人像比对成功！");
						} else {
							result.setCode(500);
							result.setMessage("人像比对不一致！");
						}
					} else {
						result.setCode(500);
						result.setMessage(outMap.get("message") + "");
					}
				} else {
					result.setCode(500);
					result.setMessage("人像比对无数据返回！");
				}
			} else {
				result.setCode(500);
				result.setMessage("人像比对失败！");
			}
		} catch (Exception e) {
			log.error("调用人像比对接口异常:", e);
			result.setCode(500);
			result.setMessage("人像比对服务异常！");
		}
		return result;
	}

	public static String base64ToBase64(String imgStr) {
		if (!StrKit.isBlank(imgStr)) {
			BASE64Decoder decoder = new BASE64Decoder();
			try {
				byte[] data = decoder.decodeBuffer(imgStr);
				// 解析数据
				for (int i = 0; i < data.length; ++i) {
					if (data[i] < 0) {
						data[i] += 256;
					}
				}
				return new String(Base64.encodeBase64(data));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return imgStr;
	}

	public static String getImgStr(String imgFile) {
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new String(Base64.encodeBase64(data));
	}

	/**
	 * 网络图片转换Base64的方法
	 *
	 * @param netImagePath
	 */
	public static String imgBase64(String imgURL) {
		ByteArrayOutputStream outPut = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		try {
			// 创建URL
			System.out.println("=====================imgURL========"+imgURL);
			URL url = new URL(imgURL);
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10 * 1000);

			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return "fail";// 连接失败/链接失效/图片不存在
			}
			InputStream inStream = conn.getInputStream();
			int len = -1;
			while ((len = inStream.read(data)) != -1) {
				outPut.write(data, 0, len);
			}
			inStream.close();
		} catch (IOException e) {
			//e.printStackTrace();
		}
		// 对字节数组Base64编码
		return java.util.Base64.getEncoder().encodeToString(outPut.toByteArray());
	}

	public static String getImgBaseStr(String imgFile) {
		if (!StrKit.isBlank(imgFile)) {
			if (imgFile.contains(".png")) {
				return "data:image/png;base64," + imgBase64(imgFile);
			} else if (imgFile.contains(".gif")) {
				return "data:image/gif;base64," + imgBase64(imgFile);
			} else if (imgFile.contains(".jpeg") || imgFile.contains(".jpg")) {
				return "data:image/jpeg;base64," + imgBase64(imgFile);
			} else if (imgFile.contains(".icon")) {
				return "data:image/x-icon;base64," + imgBase64(imgFile);
			} else {
				return "data:image/png;base64," + imgBase64(imgFile);
			}
		}
		return "";
	}
	
	public static String getImgBaseStr(String imgFile,String base64Str) {
		if (!StrKit.isBlank(imgFile) && !StrKit.isBlank(base64Str)) {
			if (base64Str.contains(".png")) {
				return "data:image/png;base64," + base64Str;
			} else if (imgFile.contains(".gif")) {
				return "data:image/gif;base64," + base64Str;
			} else if (imgFile.contains(".jpeg") || imgFile.contains(".jpg")) {
				return "data:image/jpeg;base64," + base64Str;
			} else if (imgFile.contains(".icon")) {
				return "data:image/x-icon;base64," + base64Str;
			} else {
				return "data:image/png;base64," + base64Str;
			}
		}
		return "";
	}
	
}
